using Godot;

namespace GodotThirdGame.Scripts;

public partial class Main : Node
{
    [ExportGroup("资源")]
    [Export] public PackedScene MobScene;
    
    [ExportGroup("实例")]
    [ExportSubgroup("手动指定")]
    [Export] public Hud Hud;
    [Export] public AudioStreamPlayer2D Music;
    [Export] public AudioStreamPlayer2D DeathSound;
    [ExportSubgroup("自动获取")]
    [Export] public Timer MobTimer;
    [Export] public Timer ScoreTimer;
    [Export] public Timer StartTimer;
    [Export] public Player Role;
    [Export] public Marker2D StartPosition;

    private int _score;

    public override void _Ready()
    {
        MobTimer = GetNode<Timer>("MobTimer");
        ScoreTimer = GetNode<Timer>("ScoreTimer");
        StartTimer = GetNode<Timer>("StartTimer");
        Role = GetNode<Player>("Player");
        StartPosition = GetNode<Marker2D>("StartPosition");
        
        // NewGame();
    }

    public void GameOver()
    {
        MobTimer.Stop();
        ScoreTimer.Stop();
        
        Hud.ShowGameOver();
        
        Music.Stop();
        DeathSound.Play();
    }

    public void NewGame()
    {
        GetTree().CallGroup("Mobs", Node.MethodName.QueueFree);
        
        var hud = Hud;
        hud.UpdateScore(_score);
        hud.ShowMessage("Get Ready!");
        
        StartTimer.Start();
        
        _score = 0;
        
        Role.Start(StartPosition.Position);

        Music.Play();
    }
    
    private void OnScoreTimerTimeout()
    {
        _score++;
        Hud.UpdateScore(_score);
    }

    private void OnStartTimerTimeout()
    {
        Hud.GetNode<Label>("Message").Hide();
        MobTimer.Start();
        ScoreTimer.Start();
    }
    
    private void OnMobTimerTimeout()
    {
        // Create a new instance of the Mob scene.
        Mob mob = MobScene.Instantiate<Mob>();

        // Choose a random location on Path2D.
        var mobSpawnLocation = GetNode<PathFollow2D>("MobPath/MobSpawnLocation");
        mobSpawnLocation.ProgressRatio = GD.Randf();

        // Set the mob's direction perpendicular to the path direction.
        float direction = mobSpawnLocation.Rotation + Mathf.Pi / 2;

        // Set the mob's position to a random location.
        mob.Position = mobSpawnLocation.Position;

        // Add some randomness to the direction.
        direction += (float)GD.RandRange(-Mathf.Pi / 4, Mathf.Pi / 4);
        mob.Rotation = direction;

        // Choose the velocity.
        var velocity = new Vector2((float)GD.RandRange(150.0, 250.0), 0);
        mob.LinearVelocity = velocity.Rotated(direction);

        // Spawn the mob by adding it to the Main scene.
        AddChild(mob);
    }
}